package com.learning_paicoding.utils;

import io.jsonwebtoken.*;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author hph
 * @Date 2025/10/12 16:25
 **/
public class JWTUtils {

    private static final String JWT_SECRET = "SECRET_6964@123!";

    /**
     * 创建token
     * @param userId
     * @return
     */
    public static String createToken(Long userId) {
        //头部header
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        //载荷payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userId);

        // 声明Token失效时间300s
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,300);

        //生成token
        JwtBuilder token = Jwts.builder()
                .setHeader(header)
                .setClaims(payload)
                .setExpiration(instance.getTime())
                .signWith(SignatureAlgorithm.HS256, JWT_SECRET);
        return token.compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Map<String, Object> checkToken(String token) {
        try {
            Map<String, Object> map = Jwts.parser()
                    .setSigningKey(JWT_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            return map;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        }
        return null;
    }


   /* public static void main(String[] args) {
        String token = createToken(100L);
        System.out.println(token);
        Map<String, Object> map = checkToken(token);
        System.out.println(map);
    }*/

}
